package com.jie.server.core.handler;

import com.jie.common.http.constant.HttpHeaderLineNameConstant;
import com.jie.common.http.entity.request.HttpRequest;
import com.jie.server.core.ServerApplication;
import com.jie.server.core.entity.SessionNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Objects;

/**
 * @author XieZhiJie
 * @date 2022/04/23 15:36
 */
public class InterceptorHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(InterceptorHandler.class);

    /**
     * 拦截器
     * @param key         可以通过key获取到连接的相关信息
     * @param httpRequest 请求
     * @return            拦截成功返回true, 否则返回false
     */
    public static boolean interceptor(SelectionKey key, HttpRequest httpRequest) {
        // 1.检查请求是否可直接放行
        if (ServerApplication.RELEASABLE_URL_SEY.contains(httpRequest.getUrl())) {
            return false;
        }
        try {
            // 2.检查cookie
            SocketChannel socketChannel = (SocketChannel) key.channel();
            InetSocketAddress remoteAddress = (InetSocketAddress) socketChannel.getRemoteAddress();
            String address = remoteAddress.getAddress().getHostAddress();
            int port = remoteAddress.getPort();
            Integer id = Integer.valueOf(httpRequest.getHeaderLineValue(HttpHeaderLineNameConstant.COOKIE));
            SessionNode sessionNode = ServerApplication.SESSION.get(id);
            if (sessionNode == null || !Objects.equals(sessionNode.getIp(), address) || port != sessionNode.getPort()) {
                return true;
            }
        } catch (IOException | NumberFormatException e) {
            LOGGER.warn(e.getMessage());
            return true;
        }
        return false;
    }

}
